import React, { Component } from 'react'
import { Button, Form, Input, Select, Space, Modal, message } from 'antd'
import TheButton from '@/components/TheButton'
import TheTable from '@/components/TheTable'
import ThePagination from '@/components/ThePagination'
import TheDialog from '@/components/TheDialog'
import TheUpload from '@/components/TheUpload'
import TheQueryForm from '@/components/TheQueryForm'
import TheImage from '@/components/TheImage'
import store from "@/store/store"

import {
  apiGetGoodsClassifyList,
  apiGetGoodsClassifyTree,
  apiGetBrandinfoPage,
  apiGetBrandinfoAdd,
  apiGetBrandinfoEdit,
  apiGetBrandinfoDel,
  apiCheckBrandInfo,
} from '@/request/mallManagement'
import { exportSheetTable } from '@/utils/exportTable.js';

const { TextArea } = Input;

export default class List extends Component {
  state = {
    isModalOpen: false,
    columns: [
      {
        title: '品牌名称',
        dataIndex: 'brandName',
        key: 'brandName',
      },
      {
        title: '品牌图片',
        dataIndex: 'brandImg',
        key: 'brandImg',
        render: (text, record) => {
          return <TheImage src={text} width={80} height={80} />
        },
      },
      {
        title: '品牌介绍',
        dataIndex: 'brandDetail',
        key: 'brandDetail',
        render: (text, record) => {
          return ['undefined', 'null'].includes(text) ? '' : text
        },
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
      },
      // {
      //   title: '所属类目',
      //   dataIndex: 'goodsClassifyName',
      //   key: 'goodsClassifyName',
      // },
      {
        title: '操作',
        render: (text, record) => {
          return (
            <>
              <TheButton haspermi={['mall:brandList:edit']} onClick={() => this.editDialog(record)}>
                修改
              </TheButton>
              <TheButton haspermi={['mall:brandList:delete']} onClick={() => this.delConfirm(record)}>
                删除
              </TheButton>
            </>
          )
        },
      },
    ],
    searchOption: [
      {
        field: "brandName",
        label: "品牌名称:",
        placeholder: "请输入",
        required: false,
        rules: [],
        type: "Input",
        defaultValue: "",
      }
    ],
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
    },
    total: 0,
    visible: false,
    title: '',
    type: '',
    editValue: {
      brandDetail: ''
    },
    classifyList: [],
    classifyOption: []
    , brandClassifyId: '',
    fileList: [],
    Msg: '',
    loading: false,
    searchName: ''
  }
  componentDidMount() {
    this.getClassifyList()
    this.getData()
    let searchParams = store.getState().searchValue
    if (!searchParams.brandName) {
      this.getData(searchParams.brandName)
    }
  }
  onFormSearch(values) {
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 }
    }, () => {
      this.getData(values)
    })
  }
  // getData = async (values) => {
  //   console.log(values);
  //   this.setState({
  //     searchName: values ? values.brandName : ''
  //   })
  //   if (values && values.brandName) {
  //     this.setState({
  //       pageData: {
  //         pageNo: 1,
  //         pageSize: 10,
  //       }
  //     }, () => { this.handleSearch(values) })
  //   } else {
  //     this.handleSearch(values)
  //   }
  // }
  getData = async (values) => {
    console.log(values);
    const { brandClassifyId, pageData } = this.state
    let searchParams = store.getState().searchValue

    // let { pageNo, pageSize, queryForm, pathName } = searchParams
    let res = await apiGetBrandinfoPage({ ...values, ...pageData })
    if (res.data && res.code === 0) {
      this.setState({
        dataSource: res.data,
        pageData: {
          pageNo: res.pageNo,
          pageSize: res.pageSize,
        },
        total: res.totalCount,
      }, () => {
        store.dispatch({
          type: 'SaveSearchValues',
          data: {
            ...values,
            ...this.state.pageData
          }
        })
      })
    }
  }
  getClassifyList = async () => {
    let res = await apiGetGoodsClassifyTree()
    if (res.code === 0 && res.data) {
      this.setState({
        classifyList: res.data.map((v) => {
          return {
            value: v.value,
            label: v.label,
            children: v.children.length > 0 ? v.children : []
          }
        }),
      })
    }
    let resOption = await apiGetGoodsClassifyList({ level: 2 })
    if (resOption.code === 0 && resOption.data) {
      this.setState({
        classifyOption: resOption.data.map((v) => {
          return {
            value: v.goodsClassifyId,
            label: v.goodsClassifyName,
          }
        }),
      })
    }
  }
  pageChange = (pageNo, pageSize) => {
    this.setState(
      {
        pageData: {
          pageNo,
          pageSize,
        },
      },
      () => {
        let searchParams = store.getState().searchValue

        this.getData(searchParams)
      }
    )
  }
  openDialog = () => {
    this.setState({
      visible: true,
      title: '新增商城商品品牌',
      type: 'add',
    })
  }
  editDialog = (value) => {
    let fileList = [
      {
        uid: 1,
        name: '品牌照片',
        status: 'done',
        url: value.brandImg,
      },
    ]

    this.setState({
      visible: true,
      title: '修改商城商品品牌',
      type: 'edit',
      editValue: { ...value, brandDetail: value.brandDetail ? value.brandDetail : '', brandClassifyId: value.hasOwnProperty('classifyIdStr') && value.classifyIdStr ? value.classifyIdStr.split(',') : '' },
      fileList,
    })
  }
  closeDialog = () => {
    this.setState({
      visible: false,
      title: '',
      type: '',
      editValue: {},
      fileList: [],
    })
  }
  dialogSave = async (value, types) => {

    this.setState({
      addData: value
    })
    const { editValue } = this.state

    let item = await apiCheckBrandInfo({
      ...value, brandId: editValue.brandId ? editValue.brandId : '',
    })
    if (item.data.code === 0) {
      this.BrandinfoAd(value)
    } else if (item.data.code === 1000) {
      this.setState({
        Msg: item.data.codeMessage,
        isModalOpen: true
      })

    } else if (item.data.code === 5000) {
      Modal.warning({
        content: item.data.codeMessage,
      });
    }
  }
  BrandinfoAd = async (value, types) => {

    const { type, editValue } = this.state
    if (type === 'add') {
      let res = await apiGetBrandinfoAdd({ ...value, brandDetail: value.brandDetail ? value.brandDetail : '' })
      if (res.code === 0) {
        this.closeDialog()
        React.$message({
          type: 'info',
          content: '新增成功',
        })
        this.getData()
      } else {
        this.closeDialog()
      }
    }
    if (type === 'edit') {
      let res = await apiGetBrandinfoEdit({
        brandId: editValue.brandId,
        ...value,
        brandDetail: value.brandDetail ? value.brandDetail : ''
      })
      if (res.code === 0) {
        this.closeDialog()
        React.$message({
          type: 'info',
          content: '修改成功',
        })
        this.getData()
      } else {
        this.closeDialog()
      }
    }
    this.setState({
      isModalOpen: false
    })
  }
  delConfirm = (value) => {
    React.$confirm({
      title: '删除品牌后，原关联的商品，将不再显示此品牌，是否确认删除？',
      onOk: async () => {
        let res = await apiGetBrandinfoDel({ id: value.brandId })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '删除成功',
          })
          this.getData()
        }
      },
    })
  }
  getFileResult = (file) => {
    let brandImg = file
      .map((v) => {
        if (v.response) {
          if (v.response.code === 0 && v.response.data) {
            return v.response.data
          }
        }
      })
      .join(',')
    this.formRef.setFieldsValue({ brandImg })
  }
  setSearchValue = (brandClassifyId) => {
    this.setState(
      {
        brandClassifyId: brandClassifyId || '',
        pageData: {
          pageNo: 1,
          pageSize: 10,
        },
      },
      () => {
        this.getData()
      }
    )
  }
  onReset() {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
    store.dispatch({
      type: 'SaveSearchValues',
      data: {

      }
    })
  }
  toExport = () => {
    const pageData = {
      pageNo: 1,
      pageSize: -1,
    }
    apiGetBrandinfoPage({ ...pageData }).then((res) => {
      let th_arr = [
        {
          title: '商城商品品牌',
          prop: '',
          children: [
            {
              title: '品牌名称',
              prop: 'brandName',
            },
            {
              title: '品牌图片',
              prop: 'brandImg',
            },
            {
              title: '品牌介绍',
              prop: 'brandDetail',
            },
            {
              title: '创建时间',
              prop: 'createTime',
            },
          ]
        },
      ]
      let tb_arr = res.data
      console.log(tb_arr);
      exportSheetTable({ fileName: '商城商品品牌', tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false })
      this.setState({
        selectedKeys: { 1: [] }
      })
    })
  }
  handleOk = () => {
    this.setState({
      isModalOpen: false
    })
  };
  handleCancel = () => {
    this.setState({
      isModalOpen: false
    })
  };
  hideModal = () => {
    this.setState({ isModalOpen: false })
  }

  render() {
    const {
      columns,
      dataSource,
      pageData: { pageNo, pageSize },
      total,
      isModalOpen,
      Msg,
      visible,
      title,
      editValue,
      fileList,
      addData,
      searchOption,
      loading
    } = this.state
    return (
      <div className="p-layout-box">
        <Modal visible={isModalOpen} key={Math.random()} closable={false} onCancel={this.hideModal} onOk={() => this.BrandinfoAd(addData)} >
          <p>{Msg}</p>
        </Modal>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>

          {/* <div>
            <span>所属类目：</span>
            <Select
              onChange={this.setSearchValue}
              options={classifyOption}
              style={{ width: 200 }}
              placeholder="请选择所属类目"
              allowClear
            />
          </div> */}
          <TheQueryForm
            ref={(ref) => (this.queryFormRef = ref)}
            show={true}
            option={searchOption}
            onGetValues={(values) => this.onFormSearch(values)}
            onReset={(values) => this.onReset(values)}
          ></TheQueryForm>
          <div>
            <Button type='primary' haspermi={['mall:brandList:add']} onClick={this.openDialog} style={{ marginRight: '10px' }}>新建品牌</Button>
            <TheButton size="middle" haspermi={['mall:brandList:export']} onClick={() => this.toExport()} type="default">导出</TheButton>
          </div>

        </div>
        <div className="p-layout-content-pagination">
          <TheTable columns={columns} dataSource={dataSource} />
          <ThePagination
            pageNo={pageNo}
            pageSize={pageSize}
            total={total}
            pageChange={this.pageChange}
          />
        </div>

        <TheDialog
          visible={visible}
          title={title}
          width={400}
          footer={null}
          handleCancel={this.closeDialog}>
          <Form
            labelAlign="left"
            labelCol={{ span: 6 }}
            onFinish={this.dialogSave}
            // initialValues={{ brandDetail: '' }}
            initialValues={editValue}
            ref={(ref) => (this.formRef = ref)}>
            <Form.Item
              label="名称"
              name="brandName"
              rules={[{ required: true }]}>
              <Input maxLength={20} placeholder="请输入品牌名称" />
            </Form.Item>
            <Form.Item
              name="brandImg"
              label={'品牌图片'}
              rules={[{ required: true }]}>
              <TheUpload
                isConversion={false}
                maxSize={10}
                len={1}
                fileList={fileList}
                getFileResult={this.getFileResult}
              />
            </Form.Item>
            <Form.Item
              label="品牌介绍"
              name="brandDetail">
              <TextArea
                showCount
                maxLength={100}
                style={{
                  height: 120,
                  resize: 'none',
                }}
                placeholder="请输入品牌介绍"
              />
            </Form.Item>
            <Form.Item>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'flex-end',
                  marginBottom: -30,
                }}>
                <Space>
                  <Button onClick={this.closeDialog}>取消</Button>
                  <Button type="primary" htmlType="submit" loading={loading} >
                    确认
                  </Button>
                </Space>
              </div>
            </Form.Item>
          </Form>
        </TheDialog>

      </div >
    )
  }
}
